﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DLL;
using System.Text.RegularExpressions;

namespace BLL
{
    public static class km_BLL
    {
        //创建数据库对象
        private static dbExamDataContext db = new dbExamDataContext();

        /// <summary>
        /// 获取数据源
        /// </summary>
        public static object GetSource()
        {
            return from p in db.KM select new { p.kmNum, p.kmName, kmZF = (p.kmZF == true ? "是" : "否"), p.yymm };
        }

        /// <summary>
        /// 添加科目
        /// </summary>
        /// <param name="kmName">科目名称</param>
        /// <param name="date">日期</param>
        /// <param name="zf">作废</param>
        public static bool Add(string kmName, string date, bool zf)
        {
            //记录更新状态
            bool bl = false;
            //分割字符串
            string[] strs = Regex.Split(kmName, "\\r\\n", RegexOptions.None);
            //建立对象
            KM km;
            //逐个添加
            foreach (string s in strs)
            {
                try
                {
                    //排除重复项
                    if (db.KM.Single(p => p.kmName == s).kmNum > -1)
                        continue;
                }
                catch { }
                km = new KM();
                km.kmName = s;
                km.kmZF = zf;
                km.yymm = DateTime.Parse(date);
                //指定要添加的对象
                db.KM.InsertOnSubmit(km);
                //执行添加
                db.SubmitChanges();
                bl = true;
            }
            return bl;
        }

        /// <summary>
        /// 更改数据项
        /// </summary>
        /// <param name="kmNum">编号</param>
        /// <param name="kmName">名称</param>
        /// <param name="zf">是否作废</param>
        /// <param name="date">日期</param>
        public static bool Update(string kmNum, string kmName, string date, bool zf)
        {
            //记录更新状态
            bool bl = false;
            try
            {
                //获取要更改的数据项
                KM km = db.KM.Single(p => p.kmNum == decimal.Parse(kmNum));
                km.kmName = kmName;
                km.yymm = DateTime.Parse(date);
                km.kmZF = zf;
                //提交更改
                db.SubmitChanges();
                bl = true;
            }
            catch { }
            return bl;
        }

        /// <summary>
        /// 删除数据项
        /// </summary>
        /// <param name="kmNum">要删除的数据标识</param>
        public static bool Delete(string kmNum)
        {
            db = new dbExamDataContext();
            //记录更新状态
            bool bl = false;
            //找到要删除的项
            KM km = db.KM.Single(p => p.kmNum == decimal.Parse(kmNum));
            //执行删除
            db.KM.DeleteOnSubmit(km);
            //提交更改
            db.SubmitChanges();
            return bl;
        }
    }
}
